'use client'

import { useState, useEffect } from 'react'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { DatePickerWithRange } from '@/components/DatePickerWithRange'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { toast } from 'sonner'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import type { DateRange } from 'react-day-picker'

interface User {
  id: string
  name: string
  phone: string
  points: number
  isMember: boolean
  hasPaid: boolean
  registerTime: string
}

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(false)
  const [phoneFilter, setPhoneFilter] = useState('')
  const [dateRange, setDateRange] = useState<DateRange>()
  const [editingPoints, setEditingPoints] = useState<{id: string, value: string}>({ id: '', value: '' })

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      
      if (phoneFilter) {
        params.append('phone', phoneFilter)
      }
      
      if (dateRange?.from) {
        params.append('startDate', format(dateRange.from, 'yyyy-MM-dd'))
      }
      
      if (dateRange?.to) {
        params.append('endDate', format(dateRange.to, 'yyyy-MM-dd'))
      }

      const response = await fetch(`/api/users?${params}`)
      const { success, data, message } = await response.json()
      
      if (!success) {
        throw new Error(message || '获取用户列表失败')
      }

      setUsers(data)
    } catch (error) {
      console.error('Error fetching users:', error)
      toast.error(error instanceof Error ? error.message : '获取用户列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 更新会员状态
  const handleMembershipToggle = async (userId: string, currentStatus: boolean) => {
    try {
      const response = await fetch(`/api/users/${userId}/membership`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ isMember: !currentStatus }),
      })

      const { success, message } = await response.json()
      if (!success) {
        throw new Error(message || '更新会员状态失败')
      }

      setUsers(users.map(user => 
        user.id === userId ? { ...user, isMember: !currentStatus } : user
      ))

      toast.success('会员状态更新成功')
    } catch (error) {
      console.error('Error updating membership:', error)
      toast.error(error instanceof Error ? error.message : '更新会员状态失败')
    }
  }

  // 更新积分
  const handlePointsUpdate = async (userId: string, newPoints: number) => {
    try {
      if (isNaN(newPoints) || newPoints < 0) {
        throw new Error('请输入有效的积分数值')
      }

      const response = await fetch(`/api/users/${userId}/points`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ points: newPoints }),
      })

      const { success, message } = await response.json()
      if (!success) {
        throw new Error(message || '更新积分失败')
      }

      setUsers(users.map(user => 
        user.id === userId ? { ...user, points: newPoints } : user
      ))

      setEditingPoints({ id: '', value: '' })
      toast.success('积分更新成功')
    } catch (error) {
      console.error('Error updating points:', error)
      toast.error(error instanceof Error ? error.message : '更新积分失败')
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchUsers()
  }, [])

  // 监听筛选条件变化
  useEffect(() => {
    const debounceTimeout = setTimeout(() => {
      fetchUsers()
    }, 500)

    return () => clearTimeout(debounceTimeout)
  }, [phoneFilter, dateRange])

  return (
    <div className="space-y-6 p-6">
      <Card className="p-6">
        <div className="space-y-4">
          <h2 className="text-2xl font-bold">用户管理</h2>
          
          {/* 筛选条件 */}
          <div className="flex items-center gap-4">
            <div className="flex-1 max-w-sm">
              <Input
                placeholder="输入手机号筛选"
                value={phoneFilter}
                onChange={(e) => setPhoneFilter(e.target.value)}
              />
            </div>
            <DatePickerWithRange
              value={dateRange}
              onChange={setDateRange}
            />
          </div>

          {/* 用户列表 */}
          <div className="border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户ID</TableHead>
                  <TableHead>用户名称</TableHead>
                  <TableHead>手机号</TableHead>
                  <TableHead className="text-right">积分</TableHead>
                  <TableHead>会员状态</TableHead>
                  <TableHead>支付状态</TableHead>
                  <TableHead>注册时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      <div className="flex items-center justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : users.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  users.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>{user.id}</TableCell>
                      <TableCell>{user.name}</TableCell>
                      <TableCell>{user.phone}</TableCell>
                      <TableCell className="text-right">
                        {editingPoints.id === user.id ? (
                          <div className="flex items-center justify-end gap-2">
                            <Input
                              type="number"
                              min="0"
                              value={editingPoints.value}
                              onChange={(e) => setEditingPoints({ 
                                id: user.id, 
                                value: e.target.value 
                              })}
                              className="w-24 text-right"
                            />
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handlePointsUpdate(
                                  user.id, 
                                  Number(editingPoints.value)
                                )}
                              >
                                保存
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => setEditingPoints({ id: '', value: '' })}
                              >
                                取消
                              </Button>
                            </div>
                          </div>
                        ) : (
                          <span
                            className="cursor-pointer hover:text-blue-600"
                            onClick={() => setEditingPoints({ 
                              id: user.id, 
                              value: String(user.points) 
                            })}
                          >
                            {user.points}
                          </span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Switch
                          checked={user.isMember}
                          onCheckedChange={() => handleMembershipToggle(user.id, user.isMember)}
                        />
                      </TableCell>
                      <TableCell>
                        <Badge variant={user.hasPaid ? "default" : "secondary"}>
                          {user.hasPaid ? '已支付' : '未支付'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {format(new Date(user.registerTime), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </div>
      </Card>
    </div>
  )
}

